// 初始化列表
var grid_selector = "";
var $grid_selector = "";
var pager_selector = "";
var parent_column = "";
var colNames = "";
var widthFunc = "";
var colModels = "";
//=========================================================================================================================================
// 初始化列表
var grid_selector1 = "";
var $grid_selector1 = "";
var pager_selector1 = "";
var parent_column1 = "";
var colNames1 = "";
var widthFunc1 = "";
var colModels1 = "";
$(document).ready(function () {
    $('#resourceName').click(function () {
        // 初始化列表
        grid_selector = '#grid-table';
        $grid_selector = $(grid_selector);
        pager_selector = '#grid-pager';
        parent_column = $grid_selector.closest('[class*="col-"]');
        colNames = [
            'KBP编码',
            'UNITID',
            'kbpPath',
            '资源分类',
            '资源名称',
            '资源IP'
        ];
        widthFunc = parent_column.width() / colNames.length;
        colModels = [
            {name: 'ciType', index: 'ciType', hidden: true},
            {name: 'unitId', index: 'unitId', hidden: true},
            {name: 'kbpPath', index: 'kbpPath', hidden: true},
            {name: 'kbpName', index: 'kbpName', hideWidth: 300},
            {name: 'ciName', index: 'ciName', hideWidth: 300},
            {name: 'ipAddr', index: 'ipAddr', hideWidth: 300}
        ];

        // 通过该方法来为每次弹出的模态框设置最新的zIndex值，从而使最新的modal显示在最前面
        $(document).on('show.bs.modal', '.modal', function () {
            var zIndex = 1040 + (10 * $('.modal:visible').length);
            $(this).css('z-index', zIndex);
            setTimeout(function () {
                $('.modal-backdrop').not('.modal-stack').css('z-index', zIndex - 1).addClass('modal-stack');
            }, 0);
        }).on('shown.bs.modal', function () {// 当模态框对用户可见时触发（将等待 CSS 过渡效果完成）
            $('#kpiName').val(" ");
            initKbpTable();
        });
        openKbpSelector();
    });
    //当前页面打开窗口的尺寸
    window.onresize = function () {
        changeFrameHeight();
    };
    changeFrameHeight();
});
//=========================================================================================================================================
$(document).ready(function () {
    $('#kpiName').click(function () {
        var name = $("#resourceName").val();
        if (name != null && name != " " && name.length != 0) {
            // 初始化列表
            grid_selector1 = '#grid-table1';
            $grid_selector1 = $(grid_selector1);
            pager_selector1 = '#grid-pager1';
            parent_column1 = $grid_selector1.closest('[class*="col-"]');
            colNames1 = [
                'KBP编码',
                'UNIT_ID',
                'kpiId',
                '指标名称',
                '指标ID'
            ];
            widthFunc1 = parent_column1.width() / colNames1.length;
            colModels1 = [
                {name: 'ciType', index: 'ciType', hidden: true},
                {name: 'unitId', index: 'unitId', hidden: true},
                {name: 'kpiId', index: 'kpiId', hidden: true},
                {name: 'kpiName', index: 'kpiName', hideWidth: 300},
                {name: 'kpiCode', index: 'kpiCode', hideWidth: 300}
            ];
            // 通过该方法来为每次弹出的模态框设置最新的zIndex值，从而使最新的modal显示在最前面
            $(document).on('show.bs.modal', '.modal', function () {
                var zIndex = 1040 + (10 * $('.modal:visible').length);
                $(this).css('z-index', zIndex);
                setTimeout(function () {
                    $('.modal-backdrop').not('.modal-stack').css('z-index', zIndex - 1).addClass('modal-stack');
                }, 0);
            }).on('shown.bs.modal', function () {// 当模态框对用户可见时触发（将等待 CSS 过渡效果完成）
                reloadJqGrid1();
                initKbpTable1();
            });
            openTable();
        } else {
            $(this).dynamicPop('必须先选择资源!');
        }
    });
    //当前页面打开窗口的尺寸
    window.onresize = function () {
        changeFrameHeight1();
    };
    changeFrameHeight1();
});

//=========================================================================================================================================
function changeFrameHeight() {
    var mainIframeHeight = $(window).height();
    var systemViewIframeHeight = mainIframeHeight - 72;
    $('#systemViewIframe').height(systemViewIframeHeight);
}

function changeFrameHeight1() {
    var mainIframeHeight = $(window).height();
    var systemViewIframeHeight = mainIframeHeight - 72;
    $('#systemViewIframe').height(systemViewIframeHeight);
}

function initKbpTable() {
    $grid_selector.jqGrid({
        url: ctx + '/KbpResourceData/queryPageListType',
        mtype: 'post',
        datatype: 'json',
        height: '100%',
        colNames: colNames,
        colModel: colModels,
        autowidth: true,
        altRows: true,
        rownumbers: true,
        viewrecords: true,
        multiselect: true,
        multiboxonly: true,
        rowNum: rowNum,
        rowList: rowList,
        sortname: 'ciId',
        pager: pager_selector,
        sortorder: 'asc',
        jsonReader: jsonReader,
        beforeRequest: function () {
            var postData = {};
            $('#queryPanel').find('[name^="search."]').each(function () {
                var $this = $(this);
                // console.log($this.val());
                postData[$this.attr('name').replace(/search\./, '')] = $this.val();
            });
            // 获取KBP树节点
            var selectedItems = $('#kbpTreeview').tree('selectedItems');
            if (isNotEmpty(selectedItems)) {
                postData['ciType'] = selectedItems[0].additionalParameters.id;
            } else {
                postData['ciType'] = null;
            }
            $.extend($grid_selector.getGridParam('postData'), postData);
        },
        loadComplete: function () {
            setTimeout(function () {
                $grid_selector.jqGrid('setGridParam', parent_column.width());
            }, 20);
        }
    });
}

function initKbpTable1() {
    $grid_selector1.jqGrid({
        url: ctx + '/KpiTargetData/queryPageListTarget',
        mtype: 'post',
        datatype: 'json',
        height: '100%',
        colNames: colNames1,
        colModel: colModels1,
        autowidth: true,
        altRows: true,
        rownumbers: true,
        viewrecords: true,
        multiselect: true,
        multiboxonly: true,
        rowNum: rowNum,
        rowList: rowList,
        pager: pager_selector1,
        sortname: 'kpiId',
        sortorder: 'asc',
        jsonReader: jsonReader,
        beforeRequest: function () {
            var postData = {};
            $('#queryPanel1').find('[name^="search."]').each(function () {
                var $this = $(this);
                postData[$this.attr('name').replace(/search\./, '')] = $this.val();
            });
            var rowId = $grid_selector.jqGrid('getGridParam', 'selrow');
            var rowData3 = $("#grid-table").jqGrid('getRowData', rowId);
            var test = rowData3.ciType;
            var unitId = rowData3.unitId;
            var ciType = test.substring(0, 5);
            // alert(ciType);
            if (isNotEmpty(ciType, unitId)) {
                postData['ciType'] = ciType;
                postData['unitId'] = unitId;
            } else {
                postData['ciType'] = null;
                postData['unitId'] = null;
            }
            $.extend($grid_selector1.getGridParam('postData'), postData);
            $.extend($grid_selector1.getGridParam('postData'), postData);
        },
        loadComplete: function () {
            setTimeout(function () {
                $grid_selector1.jqGrid('setGridWidth', parent_column1.width());
            }, 20);
        }
    });
}

function isNotEmpty(obj) {
    if (obj != null && obj != '' && obj != undefined) {
        return true;
    }
    return false;
}

/*点击按钮展示KBP树的节点*/
function openKbpSelector() {
    //加載KBP
    if (!$('#kbpTreeview').html()) {
        $('#kbpTreeview').ace_tree({
            dataSource: remoteKbpDateSource,
            loadingHTML: '<div class="tree-loading"><i class="ace-icon fa fa-refresh fa-spin blue"></i></div>',
            'open-icon': 'ace-icon fa fa-chevron-down',
            'close-icon': 'ace-icon fa fa-chevron-right',
            'itemSelect': true,
            'folderSelect': false,
            'multiSelect': false,
            'selected-icon': null,
            'unselected-icon': null,
            'folder-open-icon': 'ace-icon tree-plus',
            'folder-close-icon': 'ace-icon tree-minus',
            'cacheItems': false
        }).on('selected.fu.tree', function (event, data) {
            //点击KBP子节点查询所包含的资源名称
            $('#queryPanel').find('[name^="search."]').each(function () {
                var $this = $(this);
                $this.val("");
            });
            $("#grid-table").trigger("reloadGrid");
        }).on('deselected.fu.tree', function (event, data) {
            $("#grid-table").trigger("reloadGrid");
        });
    }
    $.launchDialog('popup');
}

/*点击选择指标按钮展示KPI所有指标*/
function openTable() {
    if (!$('#grid-table1').html()) {
        $("#grid-table1").trigger("reloadGrid");
        var $this = $(this);
        $this.val("");
    }
    $.launchDialog('popup1');
}

/*点击确认触发的操作*/
$('#confirm').click(function () {
    //获取选中行的id
    var rowIds = $grid_selector.jqGrid('getGridParam', 'selarrrow');
    if (rowIds == null || rowIds.length == 0) {
        $(this).dynamicPop('请选择一条记录!');
    } else if (rowIds.length > 1) {
        $(this).dynamicPop(' 不能选择多条记录, 请选择一条记录!');
    } else {
        var rowId = $grid_selector.jqGrid('getGridParam', 'selrow');
        //UNIT_ID
        var rowData = $("#grid-table").jqGrid('getRowData', rowId);
        $("#resourceName").val(rowData.ciName);
        // 最后关闭该窗口
        $('#popup').modal('hide');
    }
    // alert(url);
});

/*点击确认触发的操作1*/
$('#confirm1').click(function () {
    //获取选中行的id
    var rowIds = $grid_selector1.jqGrid('getGridParam', 'selarrrow');
    if (rowIds == null || rowIds.length == 0) {
        $(this).dynamicPop('请选择一条记录!');
    } else if (rowIds.length > 1) {
        $(this).dynamicPop(' 不能选择多条记录, 请选择一条记录!');
    } else {
        var rowId = $grid_selector1.jqGrid('getGridParam', 'selrow');
        //UNIT_ID
        var rowData = $("#grid-table1").jqGrid('getRowData', rowId);
        $("#kpiName").val(rowData.kpiName);
        // 最后关闭该窗口
        $('#popup1').modal('hide');
    }
    // alert(url);
});

//显示隐藏查询条件
$('#searBtn').click(function () {
    $(this).find('i').toggleClass('fa-arrow-down');
    $(this).find('i').toggleClass('fa-arrow-up');
});

//查询按钮
$('#searchBtn').click(function () {
    $grid_selector.trigger('reloadGrid', [{page: 1}]);
});

//查询按钮1
$('#searchBtn11').click(function () {
    $grid_selector1.trigger('reloadGrid', [{page: 1}]);
});

// 重置查询表单
$('#resetBtn').click(function () {
    $('#queryPanel').find(':input(:text)').each(function () {
        $(this).val('');
    });
    $('#queryPanel').find('input[type=checkbox],input[type=radio]').each(function () {
        $(this).removeAttr('checked');
    });
    reloadJqGrid('json');
});

// 重置查询表单1
$('#resetBtn11').click(function () {
    $('#queryPanel1').find(':input(:text)').each(function () {
        $(this).val('');
    });
    $('#queryPanel1').find('input[type=checkbox],input[type=radio]').each(function () {
        $(this).removeAttr('checked');
    });
    reloadJqGrid1('json');
});


// 重置iframe输入框
$('#resetBtn1').click(function () {
    $('#input').find(':input(:text)').each(function () {
        $(this).val('');
    });
});


// 初始化日期控件
$('.date-picker').datepicker({
    language: 'zh-CN',
    autoclose: true,//选中之后自动隐藏日期选择框
    todayHighlight: true,
    clearBtn: true,//清除按钮
    weekStart: 1,         //一周从哪一天开始
    autoclose: true,      //选择完日期后，弹出框自动关闭
    startView: 0,         //起始选择范围:0为天，1为月，2为年
    maxViewMode: 2,       //最大选择范围
    minViewMode: 0,        //最小选择范围
    forceParse: false,   //强制解析
    format: 'yyyy-mm-dd'//日期格式
}).next().on(ace.click_event, function () {
    $(this).prev().focus();
});


$('.input-daterange').datepicker({
    language: 'zh-CN',
    weekStart: 1,         //一周从哪一天开始
    autoclose: true,      //选择完日期后，弹出框自动关闭
    startView: 0,         //起始选择范围:0为天，1为月，2为年
    maxViewMode: 2,       //最大选择范围
    minViewMode: 0,        //最小选择范围
    autoclose: true,//选中之后自动隐藏日期选择框
    clearBtn: true,//清除按钮
    format: 'yyyy-mm-dd'//日期格式
});


//下拉框选择月日期控件销毁并重新加载
function dateTypeOnchange() {
    var select1 = $('#dataDimensionalitySelect option:selected').val();
    var datePakerHtml = '<div class="input-daterange input-group">\
    <input type="text" class="date-picker form-control" placeholder="选择开始时间" id="start" name="start"/>\
        <span class="input-group-addon">~</span>\
        <input type="text" class="date-picker form-control" placeholder="选择结束时间" id="end" name="end"/>\
        </div>';
    if (select1 == 'showMonth') {
        $('.date-picker').datepicker("destroy");//销毁DOM
        $('#datepaker').empty();//清空DOM
        $('#datepaker').html(datePakerHtml);//重新加载
        // 初始化日期控件
        $('.date-picker').datepicker({
            language: 'zh-CN',
            autoclose: true,//选中之后自动隐藏日期选择框
            todayHighlight: true,
            clearBtn: true,//清除按钮
            weekStart: 1,         //一周从哪一天开始
            autoclose: true,      //选择完日期后，弹出框自动关闭
            startView: 0,         //起始选择范围:0为天，1为月，2为年
            maxViewMode: 2,       //最大选择范围
            minViewMode: 1,        //最小选择范围
            forceParse: false,   //强制解析
            format: 'yyyy-mm'//日期格式
        }).next().on(ace.click_event, function () {
            $(this).prev().focus();
        });


        $('.input-daterange').datepicker({
            language: 'zh-CN',
            weekStart: 1,         //一周从哪一天开始
            autoclose: true,      //选择完日期后，弹出框自动关闭
            startView: 0,         //起始选择范围:0为天，1为月，2为年
            maxViewMode: 2,       //最大选择范围
            minViewMode: 1,        //最小选择范围
            autoclose: true,//选中之后自动隐藏日期选择框
            clearBtn: true,//清除按钮
            format: 'yyyy-mm'//日期格式
        });
    } else {
        $('.date-picker').datepicker("destroy");
        $('#datepaker').empty();
        $('#datepaker').html(datePakerHtml);
        // 初始化日期控件
        $('.date-picker').datepicker({
            language: 'zh-CN',
            autoclose: true,//选中之后自动隐藏日期选择框
            todayHighlight: true,
            clearBtn: true,//清除按钮
            weekStart: 1,         //一周从哪一天开始
            autoclose: true,      //选择完日期后，弹出框自动关闭
            startView: 0,         //起始选择范围:0为天，1为月，2为年
            maxViewMode: 2,       //最大选择范围
            minViewMode: 0,        //最小选择范围
            forceParse: false,   //强制解析
            format: 'yyyy-mm-dd'//日期格式
        }).next().on(ace.click_event, function () {
            $(this).prev().focus();
        });


        $('.input-daterange').datepicker({
            language: 'zh-CN',
            weekStart: 1,         //一周从哪一天开始
            autoclose: true,      //选择完日期后，弹出框自动关闭
            startView: 0,         //起始选择范围:0为天，1为月，2为年
            maxViewMode: 2,       //最大选择范围
            minViewMode: 0,        //最小选择范围
            autoclose: true,//选中之后自动隐藏日期选择框
            clearBtn: true,//清除按钮
            format: 'yyyy-mm-dd'//日期格式
        });
    }
}

//查询按钮的操作
$('#searchBtn1').click(function () {
    var start = $("#start").val();
    var end = $("#end").val();
    var date1 = new Date(Date.parse(start));
    var date2 = new Date(Date.parse(end));
    var date3 = date2.getTime() - date1.getTime();//时间差的毫秒数
    var days = Math.floor(date3 / (24 * 3600 * 1000));//计算出相差天数
    var select1 = $('#dataDimensionalitySelect option:selected').val();
    var name = $('#resourceName').val();
    var name1 = $('#kpiName').val();
    var bb = 123;
    if (select1 == null || select1.length == 0 || select1 == " ") {
        $(this).dynamicPop('请选择统计维度!');
    } else if (start == null || start.length == 0 || start == " " && end == null || end.length == 0 || end == " ") {
        $(this).dynamicPop('请选择时间!');
    } else if (name == null || name.length == 0 || name == " ") {
        $(this).dynamicPop('请选择资源!');
    } else if (select1 == 'showTime' && days > 0) {
        $(this).dynamicPop('按小时统计不能大于一天!');
    } else if (select1 == 'showDay' && days > 90) {
        $(this).dynamicPop('按天统计不能大于三个月!');
    } else if (select1 == 'showMonth' && days > 1095) {
        $(this).dynamicPop('按月统计不能大于三年!');
    } else if (name1 == "文件系统使用率" || name1 == "表空间使用率") {
        var rowId111 = $grid_selector.jqGrid('getGridParam', 'selrow');
        var rowId = $grid_selector1.jqGrid('getGridParam', 'selrow');
        var rowData = $("#grid-table1").jqGrid('getRowData', rowId);
        var rowData111 = $("#grid-table").jqGrid('getRowData', rowId111);
        var unitId = rowData111.unitId;
        var kpiId = rowData.kpiId;
        var kpiName = encodeURI(encodeURI(rowData.kpiName));
        var kbpPath = rowData111.kbpPath;
        var url = ctx + kbpPath + "/" + kpiId + "/" + kpiName + "/" + unitId + "/" + start + "/" + end + "/" + select1 + "/" + bb;
        // alert(url);
        $('#systemViewIframe').attr('src', url);
    } else if (name != null && name != " " && name.length != 0 && name1 != null && name1 != " " && name1.length != 0) {
        var rowId111 = $grid_selector.jqGrid('getGridParam', 'selrow');
        var rowId = $grid_selector1.jqGrid('getGridParam', 'selrow');
        var rowData = $("#grid-table1").jqGrid('getRowData', rowId);
        var rowData111 = $("#grid-table").jqGrid('getRowData', rowId111);
        var unitId = rowData111.unitId;
        var kpiId = rowData.kpiId;
        var kpiName = encodeURI(encodeURI(rowData.kpiName));
        var kbpPath = rowData111.kbpPath;
        var url = ctx + kbpPath + "/" + kpiId + "/" + kpiName + "/" + unitId + "/" + start + "/" + end + "/" + select1;
        // alert(url);
        $('#systemViewIframe').attr('src', url);
    } else if (name != null && name != " " && name.length != 0) {
        var rowIds = $grid_selector.jqGrid('getGridParam', 'selarrrow');
        var rowId = $grid_selector.jqGrid('getGridParam', 'selrow');
        //UNIT_ID
        var rowData = $("#grid-table").jqGrid('getRowData', rowId);
        var unitId = rowData.unitId;
        var kbpPath = rowData.kbpPath;
        var url = ctx + kbpPath + "/" + unitId + "/" + start + "/" + end + "/" + select1;
        // alert(url);
        $('#systemViewIframe').attr('src', url);
    }
});

// 刷新JqGrid列表
function reloadJqGrid(datatype) {
    $grid_selector.jqGrid('setGridParam', {datatype: datatype}).trigger('reloadGrid', [{page: 1}]);
}

// 刷新JqGrid1列表
function reloadJqGrid1(datatype) {
    $grid_selector1.jqGrid('setGridParam', {datatype: datatype}).trigger('reloadGrid', [{page: 1}]);
}
